package org.stw.bullfrog.ui.core
{
	import flash.display.Sprite;
	import flash.events.Event;
	
	public class BSprite extends Sprite
	{
		public var initialized:Boolean = false;
		public var destroyOnRemoval:Boolean = true;
		public var destroyed:Boolean = false;
		public var displayedAction:Function;
		public var disappearedAction:Function;
		
		public function BSprite()
		{
			super();
			this.init();
			this.addEventListener(Event.ADDED_TO_STAGE,onAddedToStageHandler);	
			this.addEventListener(Event.REMOVED_FROM_STAGE,onRemovedFromStageHandler);
		}
		
		public function init():void
		{
			if(this.initialized)
				return;
			this.initialized = true;
		}
		
		
		private function onAddedToStageHandler(event:Event):void
		{
			this.removeEventListener(Event.ADDED_TO_STAGE,onAddedToStageHandler);
			if(this.displayedAction != null)
				this.displayedAction.call();
		}
		
		private function onRemovedFromStageHandler(event:Event):void
		{
			this.removeEventListener(Event.REMOVED_FROM_STAGE,onRemovedFromStageHandler);
			if(this.disappearedAction != null)
				this.disappearedAction.call();
			if(this.destroyOnRemoval){
				this.destroy();
			}
			
		}
		
		public function removeAllChildren():void
		{
			while(this.numChildren>0){
				this.removeChildAt(0);
			}
		}
		
		public function destroy():void
		{
			if(this.destroyed)
				return;
			this.removeEventListener(Event.ADDED_TO_STAGE,onAddedToStageHandler);	
			this.removeEventListener(Event.REMOVED_FROM_STAGE,onRemovedFromStageHandler);
			
			if(this.parent)
				this.parent.removeChild(this);
			
			this.destroyed = true;
		}
	}
}